// content script in tab
//    加载对应的 inject
//    注入页面不能用 import
//


let getStorageByKey = function (key = null) {
  return new Promise(resolve => {
    chrome.storage.local.get(key, function (data) {
      if (typeof key === 'string') {
        resolve(data[key]);
      } else {
        resolve(data);
      }
    });
  });
};

init();

// 注入inject
async function init() {
  let culPage = await getCulPage();
  if (!culPage) {
    return;
  }

  function getInjectArray(inject) {
    if (Object.prototype.toString.call(inject) === '[object Array]') {
      return inject;
    }
    if (typeof inject === 'string') {
      return [inject];
    }
    if (inject) {
      // 无配置不提示
      console.error(
        `config.js中配置inject: ${inject}，类型错误，只支持Array,String`
      );
    }
    return [];
  }
  const head = document.head
    || document.getElementsByTagName('head')[0]
    || document.documentElement;

  function getScript(url) {
    const script = document.createElement('script');
    script.setAttribute('type', 'module');
    script.setAttribute('src', chrome.extension.getURL(`./inject/${url}`));
    return script;
  }

  // const script = document.createElement('script');
  // script.setAttribute('type', 'module');
  // script.setAttribute('src', chrome.extension.getURL('./common/html2canvas.js'));
  // head.insertBefore(script, head.lastChild);


  getInjectArray(culPage.inject).forEach(url => head.insertBefore(getScript(url), head.lastChild));
}


async function getCulPage() {
  let pageConfig = await getStorageByKey('pageConfig');

  let domain = window.location.hostname;

  let urlContains = [];
  pageConfig.forEach(item => {
    if (item.urlContains) {
      urlContains.push({
        inject: item.inject,
        urlContains: item.urlContains
      });
    }
  });
  let culPage = urlContains.find(item => {
    return item.urlContains.find(urlContainsItem => {
      return (
        domain.includes(urlContainsItem) || urlContainsItem.includes(domain)
      );
    });
  });
  return culPage;
}
